package com.longrise.android.byjk.plugins.productfeerate;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;

import com.bumptech.glide.Glide;
import com.longrise.android.byjk.common.FolderConstants;
import com.longrise.common.utils.PrintLog;
import com.lzy.imagepicker.bean.ImageItem;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by callxkj on 2017/6/1.
 * 产品费率presenter
 */

public class UploadProductfeeratePresenter extends UploadProductfeerateContract.Presenter {

    private static final String TAG = "UploadProductfeeratePresenter";
    private Map<String, String> mTotalImagemap; //内存中记忆的总共的图片对应地址, key:未压缩地址 vlaue:压缩后的地址
    private Map<String, String> mImagemap;  //key:未压缩的地址 value:压缩后的地址
    private Map<String, ImageItem> mImageItemmap; //key未压缩的地址 value:图片的对象
    private Map<String, ImageItem> mZipImageItemmap; //key:压缩后的地址 value:图片对象

    @Override

    protected void init() {
        mImagemap = new LinkedHashMap<>();
        mTotalImagemap = new ArrayMap<>();
        mImageItemmap = new ArrayMap<>();
        mZipImageItemmap = new LinkedHashMap<>();
    }

    @Override
    void selectFile(Context context, Uri uri) {
        String filePath = getPath(context, uri);
        PrintLog.d(TAG, "filePath:" + filePath);
        if (TextUtils.isEmpty(filePath)) {
            mView.showToast("未选取到文件");
            return;
        }
        if (filePath.endsWith(".docx") || filePath.endsWith(".pdf") || filePath.endsWith(".xlsx")
                || filePath.endsWith(".pptx") || filePath.endsWith(".doc")
                || filePath.endsWith(".xls") || filePath.endsWith(".ppt") || filePath.endsWith(".txt")) {
            File file = new File(filePath);
            long length = file.length();
            if (length > 1024 * 1024 * 10) { //10M
              mView.showToast("您选择的文件过大");
            }else{
                mView.showFile(filePath);
            }
        } else {
            mView.showToast("请选择pdf或者office文档");
        }

    }

    @Override
    void selectGalleryPic(ArrayList<ImageItem> list) {
        mImagemap.clear();
        mImageItemmap.clear();
        mZipImageItemmap.clear();
        List<String> imageneedchangelist = new ArrayList<>();
        for (ImageItem item : list) { //向压缩集合里面添加需要压缩的图片地址
            String path = item.path;
            PrintLog.d(TAG, "picpath:" + path);
            imageneedchangelist.add(path);
            mImageItemmap.put(path, item);
        }
        changeImageSize(imageneedchangelist);
        mView.showLoadingDialog();
    }

    /**
     * @param path 图片的压缩地址
     */
    @Override
    void deletePic(String path) {
        mZipImageItemmap.remove(path);
        ArrayList<ImageItem> list = new ArrayList<>();
        for (String newPath : mZipImageItemmap.keySet()) {
            list.add(mZipImageItemmap.get(newPath));
        }
        mView.resetImageItemList(list);
        selectGalleryPic(list);
    }


    /**
     * 压缩图片大小 并存储
     */
    private void changeImageSize(final List<String> pathlist) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {
                if (pathlist.size() == 0) {
                    e.onComplete();
                    return;
                }

                if (mTotalImagemap.containsKey(pathlist.get(0))) { //总集合里面包含这个图片地址则取总集合的
                    String zipPath = mTotalImagemap.get(pathlist.get(0));
                    e.onNext(zipPath);
                    return;
                }

                if (pathlist.size() > 0) {
                    String path = pathlist.get(0);
                    if (TextUtils.isEmpty(path)) {
                        return;
                    }
                    File file = new File(path);
                    try {
                        File newfile = new File(FolderConstants.PRODUCTFEE_PIC_DIR + "/" + System.currentTimeMillis() + ".jpg");
                        File parent = newfile.getParentFile();
                        if (!parent.exists()) {
                            parent.mkdirs();
                        }
                        if (newfile.exists()) {
                            newfile.delete();
                        }
                        Bitmap bitmap = Glide.with(mContext).load(file).asBitmap().into(300, 300).get();
                        FileOutputStream out = new FileOutputStream(newfile);
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                        out.flush();
                        out.close();
                        e.onNext(newfile.getAbsolutePath());
                    } catch (Exception ee) {
                        PrintLog.d(TAG, "EE:" + ee.toString());
                        e.onError(ee);
                    }
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mRxManager.addDisposable(d);
                    }

                    @Override
                    public void onNext(String value) {
                        mImagemap.put(pathlist.get(0), value);
                        mTotalImagemap.put(pathlist.get(0), value);
                        pathlist.remove(0);
                        changeImageSize(pathlist);
                    }

                    @Override
                    public void onError(Throwable e) {
                        PrintLog.d(TAG, "onError");
                        mView.dismissLoadingDialog();
                        //error处理
                        mView.showToast("选择图片失败,请重新选择图片");
                    }

                    @Override
                    public void onComplete() {
                        PrintLog.d(TAG, "onComplete");
                        List<String> newlist = new ArrayList<String>();
                        for (String key : mImagemap.keySet()) {
                            String newpath = mImagemap.get(key);
                            newlist.add(newpath);
                            //将压缩后的地址和item做一个对应关系
                            ImageItem imageItem = mImageItemmap.get(key);
                            mZipImageItemmap.put(newpath, imageItem);
                        }
                        mView.showImages(newlist);
                        mView.dismissLoadingDialog();
                    }
                });
    }


    private String getPath(Context context, Uri uri) {
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {"_data"};
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
                // Eat it  Or Log it.
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }
}
